﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ServiceTester {
    using ServiceTester.ServerRentIt11;

    public partial class frmUserMovieInfo : Form {
        public int movieId = -1;

        private MovieEntry entry;
        private RentItClient rClient;
        private UserSession uSession;

        public frmUserMovieInfo(frmUserClient fromClient, int movieId) {
            if (fromClient != null) {
                InitializeComponent();
                rClient = fromClient.rClient;
                uSession = fromClient.uSession;
                this.movieId = movieId;
            } else {
                throw new ArgumentException("A User Client Form must be specified!");
            }
        }

        private void frmUserMovieInfo_Load(object sender, EventArgs e) {
            this.GetInfo();
            txtTitle.SelectionStart = 0;
            txtTitle.SelectionLength = 0;

            if (cmbScore.Items.Count < 1) {
                foreach (var score in Enum.GetValues(typeof(Rating))) {
                    if (!score.ToString().Equals("Wrong")) {
                        cmbScore.Items.Add(score);
                    }
                }
                if (cmbScore.Items.Count > 0) cmbScore.SelectedIndex = 0;
            }
        }

        private void GetInfo() {
            btnRentHD.Enabled = false;
            btnRentSD.Enabled = false;
            entry = rClient.MovieInfo(movieId);
            this.Text = "Movie Info: " + entry.Title;
            txtTitle.Text = entry.Title;
            lblYear.Text = ""+ entry.Year;
            lblLength.Text = "" + entry.Length + " minute" + (entry.Length != 1 ? "s" : "");
            lblLanguage.Text = entry.Language;
            lblPG.Text = entry.ParentalGuidance.ToString();
            lblHD.Text = entry.HighDefinition == XBool.True ? "Yes" : "No";
            lblRelease.Text = entry.ReleaseDate.HasValue ? entry.ReleaseDate.Value.ToShortDateString() : "Unreleased";
            txtSummary.Text = entry.Summary;
            lblImdb.Text = entry.ImdbId;
            lblImdb.Links.Clear();
            lblImdb.Links.Add(0, lblImdb.Text.Length, "http://www.imdb.com/title/" + entry.ImdbId);

            lstGenre.Items.Clear();
            foreach (var genre in entry.Genre) {
                lstGenre.Items.Add(genre.Name);
            }

            picThumb.ImageLocation = "";
            picThumb.ImageLocation = entry.ThumbUrl;
            Application.DoEvents();

            btnRentSD.Enabled = !rClient.ActiveRent(movieId, uSession, false);
            if(entry.HighDefinition == XBool.True) {
                btnRentHD.Enabled = !rClient.ActiveRent(movieId, uSession, true);
            }

            this.GetRatings();
        }

        private void GetRatings() {
            var ratingScore = 0.0;
            var ratingVotes = 0.0;
            var ratings = rClient.ListMovieRatings(movieId);
            lwRatings.BeginUpdate();
            lwRatings.Items.Clear();
            foreach (var rating in ratings) {
                var lvw = new ListViewItem();
                lvw.Tag = rating;

                var ui = rClient.GetUserInfo(rating.UserId);
                lvw.Text = ui.Name;
                var score = Program.GetRatingScore(rating.Rating);
                if (score > -1) {
                    ratingScore += score;
                    ratingVotes++;
                    lvw.SubItems.Add("" + score);
                    if (rating.Comment.Length > 0) {
                        lvw.Font = new Font(lvw.Font, FontStyle.Bold);
                    }
                    lwRatings.Items.Insert(0, lvw);
                }
                Application.DoEvents();
            }
            lwRatings.EndUpdate();

            if (ratingVotes > 0) {
                var finalScore = Math.Round(ratingScore / ratingVotes, 2);
                grbRating.Text = "Rating: " + finalScore + " (" + ratingVotes + " votes)";
            }
        }

        private void btnClose_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void btnRefresh_Click(object sender, EventArgs e) {
            btnRefresh.Enabled = false;
            this.GetInfo();
            btnRefresh.Enabled = true;
            btnRefresh.Focus();
        }

        private void lblImdb_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            if(!(sender is LinkLabel)) return;
            var lnk = (LinkLabel)sender;
            lnk.Links[lnk.Links.IndexOf(e.Link)].Visited = true;
            System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
        }

        private void btnRate_Click(object sender, EventArgs e) {
            btnRate.Enabled = false;

            if (uSession != null && uSession.UserId > 0) {
                var rate = Rating.Wrong;
                Enum.TryParse(cmbScore.Text, out rate);

                var rating = new RatingEntry { UserId = this.uSession.UserId, MovieId = this.movieId, Comment = this.txtComment.Text, Rating = rate };

                var res = rClient.RateMovie(uSession, rating);

                var msg = "Thanks for rating this movie!";
                if(!res) {
                    msg = "Failed to rate movie...";
                }
                MessageBox.Show(
                    msg,
                    "Rate Result",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                if(res) {
                    this.GetRatings();
                }
            } else {
                MessageBox.Show(
                    "You have to be logged in to rate a movie!",
                    "Login Required",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }

            btnRate.Enabled = true;
        }

        private void lwRatings_Click(object sender, EventArgs e) {
            if(lwRatings.SelectedItems.Count > 0) {
                var lvw = lwRatings.SelectedItems[0];
                if(lvw.Tag is RatingEntry) {
                    var re = (RatingEntry)lvw.Tag;
                    txtViewRating.Text = re.Comment;
                    return;
                }
            }
            txtViewRating.Text = "";
        }

        private void btnRentSD_Click(object sender, EventArgs e) {
            btnRentSD.Enabled = false;
            if (uSession != null && uSession.UserId > 0) {
                var res = rClient.Rent(movieId, uSession, false);
                var msg = "Thanks for renting this movie!";
                if (!res) {
                    msg = "Failed to rent movie...";
                }
                MessageBox.Show(msg, "Rent Result", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (res) {
                    btnRefresh.PerformClick();
                    return;
                }
            } else {
                MessageBox.Show(
                    "You have to be logged in to rent a movie!",
                    "Login Required",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }

            btnRentSD.Enabled = true;
        }

        private void btnRentHD_Click(object sender, EventArgs e) {
            btnRentHD.Enabled = false;
            if (uSession != null && uSession.UserId > 0) {
                var res = rClient.Rent(movieId, uSession, true);
                var msg = "Thanks for renting this movie!";
                if (!res) {
                    msg = "Failed to rent movie...";
                }
                MessageBox.Show(msg, "Rent Result", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (res) {
                    btnRefresh.PerformClick();
                    return;
                }
            } else {
                MessageBox.Show(
                    "You have to be logged in to rent a movie!",
                    "Login Required",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }

            btnRentHD.Enabled = true;
        }
    }
}
